package com.summerbird.mallchat.common.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.summerbird.mallchat.common.user.dao.UserDao;
import com.summerbird.mallchat.common.user.domain.entity.User;
import com.summerbird.mallchat.common.user.service.UserService;
import com.summerbird.mallchat.common.user.service.WXMsgService;
import com.summerbird.mallchat.common.user.service.adapter.TextBuilder;
import com.summerbird.mallchat.common.user.service.adapter.UserAdapter;
import com.summerbird.mallchat.common.websocket.NettyUtil;
import com.summerbird.mallchat.common.websocket.service.WebSocketService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class WXMsgServiceImpl implements WXMsgService {

    /**
     * openid和登录码code的关系map
     */
    public static final ConcurrentHashMap<String, Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    @Value("${wx.mp.callback}")
    private String callback;

    public static final String URL =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private WxMpService wxMpService;

    @Autowired
    private WebSocketService webSocketService;

    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage.getEventKey());
        User user = userDao.getByOpenId(openId);
        if(Objects.isNull(code)){
            return null;
        }
        boolean registered = Objects.nonNull(user);
        boolean authorized = registered && StringUtils.isNotBlank(user.getAvatar());
        // 已经注册 并且 授权
        if(registered && authorized){
            // 登录成功，通过code向channel发送消息
            webSocketService.scanLoinSuccess(code, user.getId());
            return null;
        }
        // 不是通过扫码逻辑，而是直接关注，则直接创建新用户
        if(!registered){
            user = UserAdapter.buildUserSave(openId);
            userService.register(user);
        }
        // 推送链接给用户授权
        WAIT_AUTHORIZE_MAP.put(openId, code);
        webSocketService.waitAuthorize(code);
        String authorizeUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        return TextBuilder.build("请点击登录：<a href=\"" + authorizeUrl + "\">登录</a>", wxMpXmlMessage);
    }

    @Override
    public void authirize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        // 更新用户信息
        if(StrUtil.isBlank(user.getAvatar())){
            fillUserInfo(user.getId(), userInfo);
        }
        // 通过code找到用户channel，进行登录
        Integer code = WAIT_AUTHORIZE_MAP.get(openid);
        webSocketService.scanLoinSuccess(code, user.getId());
    }

    private void fillUserInfo(Long uid, WxOAuth2UserInfo userInfo) {
        User user = UserAdapter.buildAuthorizeUser(uid, userInfo);
        try{
            userDao.updateById(user);
        } catch (DuplicateKeyException e){
            log.error("主键冲突：{}", e);
        }
    }

    private Integer getEventKey(String eventKey) {
        try {
            String code = eventKey.replace("qrscene_", "");
            return Integer.parseInt(code);
        } catch (Exception e){
            log.error("getEventKey error:{}", e);
            return null;
        }
    }
}
